package ext.mango.aa.so;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import ext.mango.aa.eo.EOBaseCode;

import mango.Mango;
import mango.orm.DaoFactory;
import mango.orm.entity.Entity;
import mango.service.Service;

@Service
public class AppManager {
    private HashMap<String, HttpSession> usersSession = new HashMap<String, HttpSession>();
    private Long requestTimes = 0L;
    public Map<String, String> appName = new HashMap<String, String>();
    
    public void init() {
        loadAppName();
    }
    
    private void loadAppName() {
        String sql = "select * from BaseCode where codetype='appname'";
        List<Entity> es = DaoFactory.c(sql, EOBaseCode.class).listQuery();
        for(Entity e : es) {
            EOBaseCode eb = (EOBaseCode) e;
            appName.put(eb.getCode(), eb.getCodeName());
        }
    }

    public void onLogin(String userid, HttpSession session){
        usersSession.put(userid, session);
        Mango.getLog().info("SESSION ADD");
    }
    
    public void killSession(String userid) {
        HttpSession session = usersSession.get(userid);
        if (session != null) {
            try {
                usersSession.remove(userid);
                session.invalidate();
                Mango.getLog().info("SESSION:" + session.getId() + " KILLED");
            }
            catch(Exception e) {
            }
        }
    }
    
    public String getAppName(String lang) {
        return this.appName.get(lang);
    }
    
    public Long increaseRequest(){
        synchronized (requestTimes) {
            requestTimes++;
            return requestTimes;
        }
    }
    
    public Long getRequestTimes() {
        return requestTimes;
    }
    
    public int getSessions() {
        return usersSession.size();
    }
}
